<?php

/**
 * Class YWatchdog
 */
class YWatchdog extends CApplicationComponent
{
	public $table = '{{watchdog}}';

	public function write($type, $message, $variables=array())
	{
		/** @var CDbConnection $db */
		$db = Yii::app()->getDb();
		/** @var CWebUser $user */
		$user = Yii::app()->getUser();

		/** @var CHttpRequest $request */
		$request = Yii::app()->getRequest();
		$record = array(
			'user_id' => $user->getIsGuest() ? 0 : $user->getId(),
			'type' => $type,
			'message' => $message,
			'variables' => $variables,
			'location' => $request->getHostInfo() . $request->getRequestUri(),
			'referer' => $request->getUrlReferrer(),
			'hostname' => $request->getUserHostAddress(),
			'create_time' => time(),
		);
		$data = $record;
		$data['variables'] = serialize($data['variables']);
		$db->createCommand()->insert($this->table, $data);
		$this->afterWrite($record);
	}

	protected function afterWrite($record)
	{
		if ($this->hasEventHandler('onAfterWrite')) {
			$this->onAfterWrite(new CEvent($this, array('record'=>$record)));
		}
		return true;
	}

	public function onAfterWrite($event)
	{
		$this->raiseEvent('onAfterWrite', $event);
	}
}